package com.sense.kukoo.biz_me.vm

import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.sense.kukoo.common.mvvm.model.BaseMvvmModel
import com.sense.kukoo.common.mvvm.vm.BaseViewModel
import com.sense.kukoo.common.repo.Repo
import java.io.File

class ProfileViewModel : BaseViewModel() {

    private val TAG: String = javaClass.simpleName

    var oldUsername: String? = null
    var newHeaderIcon: File? = null

    val mSaveBtnEnable: MutableLiveData<Boolean> = MutableLiveData(false)
    val newUserName: MutableLiveData<String> = MutableLiveData()

    val action_editSuccess: MutableLiveData<Boolean> = MutableLiveData()

    override fun createModel(): BaseMvvmModel? = null

    override fun initData() {
        oldUsername = Repo.user.userName()
        newUserName.postValue(oldUsername)
    }

    fun checkSaveBtnEnable() {
        val nameCheck = ! oldUsername.equals(newUserName.value)
        val iconCheck = newHeaderIcon?.exists() ?: false

        mSaveBtnEnable.postValue(nameCheck || iconCheck)
    }

    fun setHeaderIcon(headerIcon: File){
        newHeaderIcon = headerIcon
        checkSaveBtnEnable()
    }

    fun setSaveUserInfo(){
        val userName = newUserName.value
        val nameCheck = ! oldUsername.equals(userName)
        val iconCheck = newHeaderIcon?.exists() ?: false
        //
        val name:String? = if(nameCheck) userName else null
        val icon:File? = if(iconCheck)newHeaderIcon else null
        //

        toView(ACTION_SHOW_DIALOG)
        request {
            //
            var avatarUrl:String? = null
            if(iconCheck){
                val uploadPic = Repo.http.uploadPic(icon!!)
                if (uploadPic.success){
                    avatarUrl = uploadPic.data
                } else {
                    Log.e(TAG, "result=" + uploadPic.msg)
                    uploadPic.msg.let { sendHintMessage(it) }
                }
            }
            //
            if(!iconCheck || (iconCheck && avatarUrl!=null)){
                val edit = Repo.http.edit(avatarUrl, name)
                if (edit.success) {
                    //编辑成功
                    val user = Repo.user.get()
                    user?.let {
                        if (name!=null) {
                            it.channelName = name
                        }
                        if (avatarUrl!=null) {
                            it.avatarUrl = avatarUrl
                        }
                        Repo.user.setUser(it)
                    }
                    action_editSuccess.postValue(true)

                } else {
                    Log.e(TAG, "result=" + edit.msg)
                    edit.msg.let { sendHintMessage(it) }
                }
            }
            //
            toView(ACTION_HIDE_DIALOG)
        }
        //
        //ToastUtils.showToast("click - Save")
        //LoggerManager.e(TAG,"nameCheck=${nameCheck}, iconCheck=${iconCheck}, name=${name}, icon=${icon}")
    }
}